package com.otod.pm.prj.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.otod.base.exception.AppException;
import com.otod.base.service.BaseService;
import com.otod.commons.auth.SessionUserUtil;
import com.otod.commons.entity.Page;
import com.otod.commons.utils.BizCodeUtil;
import com.otod.commons.utils.Collections3;
import com.otod.commons.utils.DateUtils;
import com.otod.commons.utils.StringUtils;
import com.otod.pm.constants.PmConstant;
import com.otod.pm.prj.mapper.ProjectMapper;
import com.otod.pm.prj.mapper.StepMapper;
import com.otod.pm.prj.vo.ProjectVo;
import com.otod.pm.prj.vo.StepVo;
import com.otod.pm.prj.vo.TaskVo;
import com.otod.pm.prj.vo.TeamVo;
import com.otod.sys.amcm.service.AmcmMsgAppService;
import com.otod.sys.operater.log.service.impl.OperaterLogServiceImpl;
import com.otod.sys.vo.AsmgOperaterLogVo;
import com.otod.sys.vo.AuapTEmpVo;

/**
 * 员工信息管理
 * @author jqiu
 */
@Service
@Transactional(readOnly=true)
public class ProjectService extends BaseService {
	
	@Autowired
	ProjectMapper projectMapper;
	
	@Autowired
	StepMapper stepMapper;
	
	// 
	@Autowired
	TaskService taskService;
	

	//项目团队人员管理 service
	@Autowired
	TeamService teamService;
	
	//项目对应的阶段
	@Autowired
	StepService stepService;
	
	@Autowired
	OperaterLogServiceImpl operaterLogServiceImpl;
	
	@Autowired
	private AmcmMsgAppService msgService;
	
	/**
	 * 获取项目VO
	 * @param vo
	 */
	public ProjectVo getById(String id){
		
		return projectMapper.getById(id);
	}
	
	/**
	 * 更新项目
	 */
	@Transactional
	public void updatePrj(Map<String,Object> map) throws AppException  {
		//查询项目名称是否重复
		List<ProjectVo> prloectVoList = Lists.newArrayList();
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("prjName", map.get("prjName"));
		param.put("checkPrjName","checkPrjName");
		prloectVoList = projectMapper.queryForList(param);		
		if(!prloectVoList.isEmpty()){
			//过滤掉 修改的时候 相同的名字
			ProjectVo projectVo=prloectVoList.get(0);
			if(!projectVo.getUuid().toString().equals(map.get("uuid"))){
				throw new AppException("项目名称重复 请重新填写项目名称");
			}	
			if(map.containsKey("startDate")){
				this.changePrjStartDate(projectVo);
			}
		}
		
		//通过uuid 查询数据
		ProjectVo vo = new ProjectVo();
		if (null == map.get("uuid")) {
			throw new AppException("修改项目有误请确认");
		}
		vo = this.getById((String)map.get("uuid"));
		
		List<AsmgOperaterLogVo> asmgOperaterLogList = new ArrayList<AsmgOperaterLogVo>();
		
		//项目 名称
		if(!StringUtils.equals(vo.getPrjName(), (String)map.get("prjName"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			
			mapDepice.put("key", "项目名称");
			mapDepice.put("oVal", vo.getPrjName());
			mapDepice.put("nVal", map.get("prjName"));
			
			String depice = "[{\"key\":\"项目名称\""+",\"oVal\":"+"\""+vo.getPrjName()+"\""+",\"nVal\":"+"\""+map.get("prjName")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);	
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
		
		// 项目设计号	
	  	if(!StringUtils.equals(vo.getPrjNo(), (String)map.get("prjNo"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "项目设计号");
			mapDepice.put("oVal", vo.getPrjNo());
			mapDepice.put("nVal", map.get("prjNo"));
			String depice = "[{\"key\":\"项目设计号\""+",\"oVal\":"+"\""+vo.getPrjNo()+"\""+",\"nVal\":"+"\""+map.get("prjNo")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	  	// 项目规模
	  	if(!StringUtils.equals(vo.getProjectSize(), (String)map.get("projectSize"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "项目规模");
			mapDepice.put("oVal", vo.getProjectSize());
			mapDepice.put("nVal", map.get("projectSize"));
			String depice = "[{\"key\":\"项目规模\""+",\"oVal\":"+"\""+vo.getProjectSize()+"\""+",\"nVal\":"+"\""+map.get("projectSize")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	  	// 客户名称
	  	if(!StringUtils.equals(vo.getCustNo(), (String)map.get("custNo"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "客户名称");
			mapDepice.put("oVal", vo.getCustNo());
			mapDepice.put("nVal", map.get("custNo"));
			String depice = "[{\"key\":\"客户名称\""+",\"oVal\":"+"\""+vo.getCustNo()+"\""+",\"nVal\":"+"\""+map.get("custNo")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	 // 投资额
	  	if(!StringUtils.equals(vo.getInvest(), (String)map.get("invest"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "投资额");
			mapDepice.put("oVal", vo.getInvest());
			mapDepice.put("nVal", map.get("invest"));
			String depice = "[{\"key\":\"投资额\""+",\"oVal\":"+"\""+vo.getInvest()+"\""+",\"nVal\":"+"\""+map.get("invest")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	 // 投资单位
	  	if(!StringUtils.equals(vo.getInvestment(), (String)map.get("investment"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "投资单位");
			mapDepice.put("oVal", vo.getInvestment());
			mapDepice.put("nVal", map.get("investment"));
			String depice = "[{\"key\":\"投资单位\""+",\"oVal\":"+"\""+vo.getInvestment()+"\""+",\"nVal\":"+"\""+map.get("investment")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	  	 // 合同额
	  	if(!StringUtils.equals(vo.getContracts(), (String)map.get("contracts"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "合同额");
			mapDepice.put("oVal", vo.getContracts());
			mapDepice.put("nVal", map.get("contracts"));
			String depice = "[{\"key\":\"合同额\""+",\"oVal\":"+"\""+vo.getContracts()+"\""+",\"nVal\":"+"\""+map.get("contracts")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	  	 // 合同编号
	  	if(!StringUtils.equals(vo.getContractno(), (String)map.get("contractno"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "合同编号");
			mapDepice.put("oVal", vo.getContractno());
			mapDepice.put("nVal", map.get("contractno"));
			String depice = "[{\"key\":\"合同编号\""+",\"oVal\":"+"\""+vo.getContractno()+"\""+",\"nVal\":"+"\""+map.get("contractno")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	

	  	//项目结束时间
	  	int prjDateNumber = DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(vo.getEndDate(),"yyyyMMdd"), DateUtils.formatDate((Date)map.get("endDate"),"yyyyMMdd"));
	  	if(prjDateNumber != 0) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			String depice = "[{\"key\":\"项目结束时间\""+",\"oVal\":"+"\""+DateUtils.formatDate(vo.getEndDate())+"\""+",\"nVal\":"+"\""+DateUtils.formatDate((Date)map.get("endDate"))+"\"}]";
			asmgOperaterLogVo.setDepict(depice);	
			
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
	  	
	  	
	   //承接单位
	  if(!StringUtils.equals(vo.getTakeUnit(), (String)map.get("takeUnit"))) {
			AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
			asmgOperaterLogVo  = setOperaterLogValue((String)map.get("uuid"));
			Map<String, Object> mapDepice = new HashMap<String, Object>();
			mapDepice.put("key", "承接单位");
			mapDepice.put("oVal", vo.getTakeUnit());
			mapDepice.put("nVal", map.get("takeUnit"));
			String depice = "[{\"key\":\"承接单位\""+",\"oVal\":"+"\""+vo.getTakeUnit()+"\""+",\"nVal\":"+"\""+map.get("takeUnit")+"\"}]";
			asmgOperaterLogVo.setDepict(depice);
			asmgOperaterLogList.add(asmgOperaterLogVo);
		}
		projectMapper.update(map);
		for (AsmgOperaterLogVo asmgOperaterLogVo : asmgOperaterLogList) {
			operaterLogServiceImpl.addLog(asmgOperaterLogVo);
		}
	}
	
	
	// 日志基础方法
	private AsmgOperaterLogVo setOperaterLogValue(String id){
		AsmgOperaterLogVo asmgOperaterLogVo = new AsmgOperaterLogVo();
		asmgOperaterLogVo.setEmpNo(SessionUserUtil.getCurrentUser().getUserNo());
		asmgOperaterLogVo.setEmpName(SessionUserUtil.getCurrentUser().getUserName());
		asmgOperaterLogVo.setIpaddr(SessionUserUtil.getCurrentUser().getLoginIp());
		asmgOperaterLogVo.setBusiModule("PM");
		asmgOperaterLogVo.setBusiFunc("PM_001005");
		asmgOperaterLogVo.setBusiId(id);
		asmgOperaterLogVo.setOperaterType("50010001");
		asmgOperaterLogVo.setLogTm(DateUtils.getCurrentDate());
		return asmgOperaterLogVo;
	}
	
	
	/**
	 * 新增项目
	 */
	@Transactional
	public void addPrj(ProjectVo vo) throws AppException {
		//查询项目名称是否重复
		List<ProjectVo> prloectVoList = Lists.newArrayList();
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("prjName", vo.getPrjName());
		param.put("checkPrjName","checkPrjName");
		prloectVoList = projectMapper.queryForList(param);
		if(!prloectVoList.isEmpty()){
			throw new AppException("项目名称重复 请重新填写项目名称");
		}
		vo.setUuid(super.getUUID());
		vo.setStatus(PmConstant.PRJ_STATUS_WAITING);
		projectMapper.insert(vo);
		//添加项目默认负责人信息（默认创建人为项目负责人
			TeamVo teamVo = new TeamVo();
			teamVo.setPrjId(vo.getUuid());
			teamVo.setEmpNo(vo.getCreateEmpNo());
			teamVo.setRoleNo(PmConstant.PRJ_ROLE_PRINCIPAL);
			teamService.addTeam(teamVo);
	}
	
	/**
	 * 查询项目信息列表
	 * @param param	参数
	 * @return	分页信息和结果数据
	 */
	public List<ProjectVo> queryForList(Map<String,Object> param){
		List<ProjectVo> dataList =  projectMapper.queryForList(param);
		return dataList;
	}
	
	
	/**
	 * 分页查询项目信息列表
	 * @param page	分页信息
	 * @param param	参数
	 * @return	分页信息和结果数据
	 */
	public Page queryForList(Page page,Map<String,Object> param){
		List<ProjectVo> dataList =  projectMapper.queryForList(page,param);
		for (ProjectVo projectVo : dataList) {
			//项目经理
			if (StringUtils.equals(PmConstant.PRJ_ROLE_MANAGER, projectVo.getRoleNo())) {
				projectVo.setTrainsRoleNo("项目经理");
				//项目负责人
			} else if (StringUtils.equals(PmConstant.PRJ_ROLE_PRINCIPAL, projectVo.getRoleNo())) {
				projectVo.setTrainsRoleNo("项目负责人");
				//项目成员
			} else if (StringUtils.equals(PmConstant.PRJ_ROLE_MEMBER, projectVo.getRoleNo())) {
				projectVo.setTrainsRoleNo("项目成员");
				//工作室主任
			} else if (StringUtils.equals(PmConstant.PRJ_ROLE_CHARGE, projectVo.getRoleNo())) {
				projectVo.setTrainsRoleNo("工作室主任");
				// 总师
			} else if (StringUtils.equals(PmConstant.PRJ_ROLE_ENTIRE, projectVo.getRoleNo())) {
				projectVo.setTrainsRoleNo("项目总师");
				
			} else if (StringUtils.equals(PmConstant.PRJ_ROLE_ADMIN, projectVo.getRoleNo())) {
				projectVo.setTrainsRoleNo("项目管理员");
				
			}else if (StringUtils.equals(PmConstant.PRJ_ROLE_CHECK, projectVo.getRoleNo())){
				projectVo.setTrainsRoleNo("项目校对");
			}else {
				projectVo.setTrainsRoleNo("无");
			 }
			projectVo.setManagerName(teamService.getManagerNameInPrj(projectVo.getUuid(), PmConstant.PRJ_ROLE_PRINCIPAL));
			
		}
		page.setAaData(this.setProjectVo(dataList));
		return page;
	}
	
	/**
	 * 重新组装页面数据
	 * 
	 */
	
	public List<ProjectVo> setProjectVo(List<ProjectVo> list){
		
		for (ProjectVo vo : list) {
			String prjType = vo.getPrjType();
			if(StringUtils.isNotEmpty(prjType)){
				vo.setPrjType(BizCodeUtil.getBizCodeNameByNo("pmProjectType", prjType));
			}
			String prjLvl = vo.getPrjLvl();
			if(StringUtils.isNotEmpty(prjLvl)){
				vo.setPrjLvl(BizCodeUtil.getBizCodeNameByNo("pmPrjLvl", prjLvl));
			}
			String status = vo.getStatus();
			if(StringUtils.isNotEmpty(status)){
				vo.setStatusName(BizCodeUtil.getBizCodeNameByNo("pmProjectStatus", status));
			}
		}
		
		return list;
	}
	/**
	 * 删除项目
	 */
	@Transactional
	public void delPrj(String id) {
		//删除项目
		projectMapper.deleteById(id);
	}
	/**
	 * 逻辑删除  修改标志位
	 * @param id 项目id
	 * @throws AppException 
	 */
	@Transactional
	public void removePrj(Map<String, Object> map, String id) throws AppException{
		map.put("isDel", "20000001");
		if (StringUtils.isEmpty(id)) {
			throw new AppException("请正确选择项目");
		}
		
		// 项目删除
		map.put("uuid", id);
		update(map);
		
		// 项目团队人员管理
		map.remove("uuid");
		map.put("prjId", id);
		teamService.remove(map);		
		// 删除阶段 pm_t_step表
		stepService.remove(map);;
		// 删除任务
		
		taskService.remove(map);
		
	}
	/**
	 * 修改项目
	 */
	@Transactional
	public void update(Map<String,Object> map) {
		//修改项目
		projectMapper.update(map);
		
	}
	/**
	 * 开始项目
	 */
	@Transactional
	public void beginProject(Map<String,Object> map) {
		//修改项目
		projectMapper.update(map);
		Map<String,Object> newMap = new HashMap<String,Object>();
		newMap.put("prjId", map.get("uuid"));
		List<TaskVo> taskList = taskService.queryTaskList(newMap);
		List<StepVo> stepList = stepService.queryStepVoList(map.get("uuid").toString());
		
		for (StepVo stepVo : stepList) {
			if(stepVo.getSort() == 1 && PmConstant.STEP_STATUS_READY.equals(stepVo.getStatus())){
				map = new HashMap<String,Object>();
				map.put("uuid", stepVo.getUuid());
				map.put("status", PmConstant.STEP_STATUS_STARTING);
				stepService.update(map);
			}
		}
		for (TaskVo taskVo : taskList) {
			int days = DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(taskVo.getStartDate(), "yyyyMMdd"), DateUtils.getDate("yyyyMMdd"));
			if(days==0 && StringUtils.isNotEmpty(taskVo.getEmpNo())
					&& PmConstant.TASK_STATUS_READY.equals(taskVo.getStatus())){
				
				map = new HashMap<String,Object>();
				map.put("uuid", taskVo.getUuid());
				map.put("status", PmConstant.TASK_STATUS_STARTING);
				taskService.update(map);
				msgService.installMsgVo(taskVo,taskVo.getTaskName()+"任务 ：开始时间到了，任务已经自动开始！");
			}
			int endDays = DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(taskVo.getPlanEndDate(), "yyyyMMdd"), DateUtils.getDate("yyyyMMdd"));
			if(endDays==0 && StringUtils.isNotEmpty(taskVo.getEmpNo())
					&& PmConstant.TASK_STATUS_STARTING.equals(taskVo.getStatus())){
				msgService.installMsgVo(taskVo,taskVo.getTaskName()+"任务 ： 结束时间到了，请提交任务");
			}
		}
	}
	/**
	 * 查询全部项目
	 * @param id
	 */
	public List<ProjectVo> findAll(){
		return projectMapper.queryForList(new HashMap<String, Object>());
	}
	

	/**
	 * 通过项目名字查询 项目的id
	 * @param prjType
	 * @return
	 */
	public ProjectVo selectProjectUuid(String prjType){
		ProjectVo m = projectMapper.selectProjectUuid(prjType);
		return m;
	}
	/**
	 * 通过项目和项目类型名字查询数据
	 * @param prjType
	 * @return
	 */
	public ProjectVo selectProject(String prjType,String prjName){
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("prjType", prjType);
		param.put("prjName", prjName);
		return projectMapper.selectProject(prjType,prjName);
		
	}
	/**
	 * 
	 * @param emp
	 * @param stuts
	 * @return
	 */
	public List<ProjectVo> queryPrjUuidEmp(String empNo,String status){
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("empNo", empNo);
		param.put("status", status);
		return projectMapper.queryForList(param);
	}
	
	/**
	 * 查询本项目还可添加的人员列表
	 * @param prjId
	 * @return List<AuapTEmpVo>
	 */
	public List<AuapTEmpVo> findEmpNotInTeam(String prjId){
		List<AuapTEmpVo> list =  projectMapper.selectEmpNotInPrj(prjId);
		return list;
	}
	
	/**
	 * 设置项目阶段状态
	 * @param vo status
	 * @return ProjectVo
	 */
	@Transactional
	public void changePrjStatus(String prjId,String status){
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("uuid", prjId);
		map.put("status", status);
		projectMapper.update(map);
	}
	

	/**
	 * 项目时间改变，相应阶段，任务的时间状态改变
	 * 
	 */
	@Transactional
	public void changePrjStartDate(ProjectVo vo){
		Date date = vo.getStartDate();
		Map<String,Object> params = new HashMap<String,Object>();
		params.put("sort", 1);
		params.put("prjId", vo.getUuid());
		List<StepVo> stepList =  stepMapper.queryForList(params);
		if(Collections3.isNotEmpty(stepList)){
			StepVo stepVo = stepList.get(0);
			params.clear();
			params.put("uuid", stepVo.getUuid());
			params.put("startDate", date);
			if(DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(date, "yyyyMMdd"),DateUtils.getDate("yyyyMMdd"))>0){
				params.put("status", PmConstant.STEP_STATUS_READY);
			}else{
				params.put("status",PmConstant.STEP_STATUS_STARTING);
			}
			stepMapper.update(params);
			
			List<TaskVo> taskVoList = taskService.queryValidList(stepVo.getUuid());
			
			for (TaskVo taskVo : taskVoList) {
				if(stepVo.getStartDate()==taskVo.getStartDate()){
					params.clear();
					params.put("uuid", taskVo.getUuid());
					params.put("startDate", date);
					if(DateUtils.getDaysBetweenTwoDates(DateUtils.formatDate(date, "yyyyMMdd"),DateUtils.getDate("yyyyMMdd"))>0){
						params.put("status", PmConstant.TASK_STATUS_READY);
					}else{
						params.put("status",PmConstant.TASK_STATUS_STARTING);
					}
					taskService.update(params);
				}
			}
			
		}
		
		
		
	}
	

	/**
	 * 通过empNo查询
	 * @param empNo
	 * @return
	 */
	public List<ProjectVo> queryEmpNo(String empNo){
		Map<String, Object> param = new HashMap<String,Object>();
		param.put("empNo", empNo);
		
		return projectMapper.queryForList(param);
	}
	


	
}
